import { useEffect, useRef, useState } from "react";
import style from "./index.module.css";
import { Button, Input, NavBar, Toast } from "antd-mobile";
function Search() {
    const [list, setList] = useState([]);
    const [value, setValue] = useState("");
    const user_id = "客服1";
    const server_id = 4567;
    const socketRef = useRef(null);
    const heartbeatRef = useRef(null);
    const timeoutRef = useRef(null);
    const heartbeat = () => {
        heartbeatRef.current = setInterval(() => {
            socketRef.current.send(
                JSON.stringify({
                    type: "heartbeat",
                })
            );
        }, 3000);
        timeoutRef.current = setInterval(() => {
            const oldTime = localStorage.getItem("heartbeat");
            const newTime = Date.now();
            if (newTime - oldTime > 20000) {
                clearInterval(heartbeatRef.current);
                clearInterval(timeoutRef.current);
                socketRef.current.close();
                setTimeout(() => {
                    connction();
                }, 5000);
            }
        }, 10000);
    };
    const connction = () => {
        socketRef.current = new WebSocket(
            `ws://115.190.7.15:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
        );
        socketRef.current.onopen = () => {
            socketRef.current.send(JSON.stringify({ type: "getChatList" }));
            heartbeat();
        };
        socketRef.current.onerror = () => {
            console.log("连接失败");
            setTimeout(() => {
                connction();
            }, 5000);
        };
        socketRef.current.onmessage = (e) => {
            const { type, data } = JSON.parse(e.data);
            if (type === "heartbeat") {
                localStorage.setItem("heartbeat", Date.now().toString());
            } else if (type === "getChatList") {
                setList(data);
            }
            else if (type === "addMessage") {
                setList((prev) => {
                    return [...prev, data];
                });
            }
        };
        socketRef.current.onclose = () => {
            console.log("连接关闭");
        };
    };
    useEffect(() => {
        connction();
        return () => {
            socketRef.current.close();
            clearInterval(heartbeatRef.current);
            clearInterval(timeoutRef.current);
        };
    }, []);
    const sendMessageFn = () => {
        const trim = value.trim();
        if (!trim) {
            Toast.show({
                content: "请输入内容",
                position: "bottom",
            });
            setValue("");
            return;
        }
        socketRef.current.send(
            JSON.stringify({
                type: "addMessage",
                data: {
                    message: value,
                },
            })
        );
        setValue("");
    };
    const divRef = useRef(null);
    useEffect(() => {
        divRef.current.scrollTop = divRef.current.scrollHeight;
    }, [list]);
    const sendImageFn = () => {
        const input = document.createElement("input");
        input.type = "file";
        input.onchange = (e) => {
            const file = e.target.files[0];
            if (file.size > 500 * 1024) {
                alert("图片过大");
                return;
            }
            const fr = new FileReader();
            fr.onload = (data) => {
                console.log(data.target.result);
                const msg = { type: "addMessage", data: { message: data.target.result, type: 'image' } }

                socketRef.current.send(
                    JSON.stringify(msg)
                );
            };
            fr.readAsDataURL(file);
        };
        input.click();
    };
    return (
        <div className={style.box}>
            <NavBar>客服1</NavBar>
            <div ref={divRef} className={style.list}>
                {list.map((item, index) => {
                    return (
                        <div
                            key={index}
                            className={
                                item.user_id === user_id ? style.right : ""
                            }
                        >
                            <img
                                src={
                                    item.user_id === user_id
                                        ? item.other_avatar
                                        : item.user_avatar
                                }
                                alt=""
                            />
                            <p>
                                {
                                    item.type === "image" ? <img src={item.message} style={{ maxWidth: '40vw' }} /> : item.message
                                }
                            </p>
                        </div>
                    );
                })}
            </div>
            <div className={style.footer}>
                <Input
                    className={style.input}
                    value={value}
                    onChange={(val) => {
                        setValue(val);
                    }}
                />
                <Button size="mini" color="warning" onClick={sendImageFn}>
                    发图片
                </Button>
                <Button size="mini" color="primary" onClick={sendMessageFn}>
                    发送消息
                </Button>
            </div>
        </div>
    );
}

export default Search;
